/**
 * Development Assistant
 *
 * 轻量级开发助手 - 专为本地MCP工具设计的简化监控
 * 专注于开发时的调试信息和性能分析
 */

const fs = require('fs');
const path = require('path');
const { getLogger } = require('../logging/logger');

class DevelopmentAssistant {
    constructor(options = {}) {
        this.options = {
            enabled: options.enabled || process.env.VISION_DEBUG === 'true',
            logFile: options.logFile || path.join(process.cwd(), 'vision-analyzer.log'),
            maxLogSize: options.maxLogSize || 1024 * 1024, // 1MB
            maxHistoryEntries: options.maxHistoryEntries || 100,
            ...options
        };

        this.logger = getLogger('development-assistant');
        this.history = [];
        this.startTime = Date.now();
        this.requestCount = 0;
        this.lastCleanup = Date.now();
    }

    /**
     * 初始化开发助手
     */
    initialize() {
        if (!this.options.enabled) {
            this.logger.debug('Development assistant is disabled');
            return;
        }

        this.logger.info('Development assistant initialized');
        this.cleanupOldLogs();
    }

    /**
     * 记录操作开始
     */
    startOperation(operation, context = {}) {
        if (!this.options.enabled) return;

        const entry = {
            id: ++this.requestCount,
            operation,
            startTime: Date.now(),
            startMemory: process.memoryUsage(),
            context: this.sanitizeContext(context)
        };

        this.history.push(entry);
        this.logOperation('START', operation, entry);
        return entry.id;
    }

    /**
     * 记录操作完成
     */
    endOperation(operationId, result = null, error = null) {
        if (!this.options.enabled) return;

        const entry = this.history.find(e => e.id === operationId);
        if (!entry) return;

        entry.endTime = Date.now();
        entry.duration = entry.endTime - entry.startTime;
        entry.endMemory = process.memoryUsage();
        entry.success = !error;
        entry.error = error ? this.sanitizeError(error) : null;
        entry.result = result ? this.sanitizeResult(result) : null;

        this.logOperation('END', entry.operation, entry);
        this.cleanupHistory();
    }

    /**
     * 记录错误
     */
    logError(operation, error, context = {}) {
        if (!this.options.enabled) return;

        const errorEntry = {
            timestamp: Date.now(),
            operation,
            error: this.sanitizeError(error),
            context: this.sanitizeContext(context)
        };

        this.appendToFile('ERROR', errorEntry);
        this.logger.error(`Operation failed: ${operation}`, { error: error.message });
    }

    /**
     * 获取性能统计
     */
    getPerformanceStats() {
        if (!this.options.enabled) return null;

        const now = Date.now();
        const uptime = now - this.startTime;
        const recentOperations = this.history.slice(-10);

        const stats = {
            uptime,
            totalRequests: this.history.length,
            successRate: this.calculateSuccessRate(),
            averageResponseTime: this.calculateAverageResponseTime(),
            recentOperations: recentOperations.map(op => ({
                operation: op.operation,
                duration: op.duration,
                success: op.success
            })),
            memoryUsage: process.memoryUsage(),
            timestamp: now
        };

        return stats;
    }

    /**
     * 获取健康状态
     */
    getHealthStatus() {
        const memUsage = process.memoryUsage();
        const uptime = Date.now() - this.startTime;

        // 简化的健康检查
        const isHealthy = memUsage.heapUsed < 500 * 1024 * 1024 && // 500MB
                         uptime > 0; // 服务已启动

        return {
            status: isHealthy ? 'healthy' : 'warning',
            uptime,
            memoryUsage: {
                heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024) + 'MB',
                heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024) + 'MB',
                external: Math.round(memUsage.external / 1024 / 1024) + 'MB'
            },
            requestCount: this.history.length,
            timestamp: Date.now()
        };
    }

    /**
     * 生成开发报告
     */
    generateReport() {
        if (!this.options.enabled) return 'Development assistant is disabled';

        const stats = this.getPerformanceStats();
        const health = this.getHealthStatus();

        return this.formatReport(stats, health);
    }

    /**
     * 记录操作到文件
     */
    logOperation(type, operation, data) {
        const logEntry = {
            timestamp: new Date().toISOString(),
            type,
            operation,
            data
        };

        this.appendToFile(type, logEntry);
    }

    /**
     * 追加日志到文件
     */
    appendToFile(type, data) {
        try {
            // 检查日志文件大小
            if (fs.existsSync(this.options.logFile)) {
                const stats = fs.statSync(this.options.logFile);
                if (stats.size > this.options.maxLogSize) {
                    this.rotateLogFile();
                }
            }

            const logLine = JSON.stringify({ timestamp: Date.now(), type, ...data }) + '\n';
            fs.appendFileSync(this.options.logFile, logLine);
        } catch (error) {
            this.logger.error('Failed to write to log file:', { error: error.message });
        }
    }

    /**
     * 轮转日志文件
     */
    rotateLogFile() {
        try {
            const backupFile = this.options.logFile + '.old';
            if (fs.existsSync(this.options.logFile)) {
                fs.renameSync(this.options.logFile, backupFile);
            }
        } catch (error) {
            this.logger.error('Failed to rotate log file:', { error: error.message });
        }
    }

    /**
     * 清理旧日志
     */
    cleanupOldLogs() {
        try {
            const logFile = this.options.logFile;
            const oldLogFile = logFile + '.old';

            if (fs.existsSync(oldLogFile)) {
                const stats = fs.statSync(oldLogFile);
                const daysSinceCreation = (Date.now() - stats.mtime.getTime()) / (1000 * 60 * 60 * 24);

                if (daysSinceCreation > 7) { // 保留7天
                    fs.unlinkSync(oldLogFile);
                }
            }
        } catch (error) {
            this.logger.error('Failed to cleanup old logs:', { error: error.message });
        }
    }

    /**
     * 清理历史记录
     */
    cleanupHistory() {
        const now = Date.now();
        if (now - this.lastCleanup > 60000) { // 每分钟清理一次
            this.history = this.history.slice(-this.options.maxHistoryEntries);
            this.lastCleanup = now;
        }
    }

    /**
     * 计算成功率
     */
    calculateSuccessRate() {
        if (this.history.length === 0) return 100;

        const successful = this.history.filter(op => op.success).length;
        return Math.round((successful / this.history.length) * 100);
    }

    /**
     * 计算平均响应时间
     */
    calculateAverageResponseTime() {
        const completedOps = this.history.filter(op => op.duration !== undefined);
        if (completedOps.length === 0) return 0;

        const totalTime = completedOps.reduce((sum, op) => sum + op.duration, 0);
        return Math.round(totalTime / completedOps.length);
    }

    /**
     * 清理上下文信息（移除敏感数据）
     */
    sanitizeContext(context) {
        if (!context || typeof context !== 'object') return context;

        const sanitized = { ...context };
        const sensitiveKeys = ['api_key', 'token', 'password', 'secret'];

        for (const key of sensitiveKeys) {
            if (sanitized[key]) {
                sanitized[key] = '[REDACTED]';
            }
        }

        return sanitized;
    }

    /**
     * 清理错误信息
     */
    sanitizeError(error) {
        return {
            name: error.name,
            message: error.message,
            stack: error.stack ? error.stack.split('\n').slice(0, 5).join('\n') : null
        };
    }

    /**
     * 清理结果信息
     */
    sanitizeResult(result) {
        if (typeof result === 'string') {
            return result.length > 200 ? result.substring(0, 200) + '...' : result;
        }
        return '[Object]';
    }

    /**
     * 格式化报告
     */
    formatReport(stats, health) {
        const lines = [
            '📊 Vision Analyzer Development Report',
            '====================================',
            '',
            `⏱️  Uptime: ${Math.round(stats.uptime / 1000)}s`,
            `📈 Total Requests: ${stats.totalRequests}`,
            `✅ Success Rate: ${stats.successRate}%`,
            `⚡ Avg Response Time: ${stats.averageResponseTime}ms`,
            '',
            '💾 Memory Usage:',
            `   Heap Used: ${health.memoryUsage.heapUsed}`,
            `   Heap Total: ${health.memoryUsage.heapTotal}`,
            '',
            '🔍 Recent Operations:',
            ...stats.recentOperations.map(op =>
                `   ${op.operation}: ${op.duration}ms (${op.success ? '✅' : '❌'})`
            ),
            '',
            `📝 Detailed logs: ${this.options.logFile}`,
            `🕐 Generated: ${new Date().toISOString()}`
        ];

        return lines.join('\n');
    }

    /**
     * 关闭开发助手
     */
    shutdown() {
        if (this.options.enabled) {
            this.logger.info('Development assistant shutdown');

            // 生成最终报告
            const report = this.generateReport();
            this.appendToFile('SHUTDOWN', { report });
        }
    }
}

module.exports = DevelopmentAssistant;